package com.example.boss.pinkdiary;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;


import android.text.Editable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import android.widget.TextView;
import android.widget.TimePicker;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.text.TextWatcher;
import android.widget.Toast;

import com.cocosw.bottomsheet.BottomSheet;
import com.example.boss.db.gen.DaoMaster;
import com.example.boss.db.gen.DaoSession;
import com.example.boss.db.gen.diaryList;
import com.example.boss.db.gen.diaryListDao;
import com.example.boss.db.gen.diaryTag;
import com.example.boss.db.gen.diaryTagDao;
import com.example.boss.db.gen.greenDaoManager;

import org.greenrobot.greendao.query.QueryBuilder;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import static android.R.attr.password;

/**
 * Created by 打好boss on 2018/6/9.
 */

public class PinkWrite extends AppCompatActivity{
    private TextView time1,time2;//显示在actionbar的当前时间
    private android.support.v7.app.ActionBar actionBar;
    private int year,month,day,hour,minute,second;
    private int get_year,get_month,get_day;
    private String n_hour,n_minute;
    private String get_hour,get_minute;
    private Calendar calendar;
    private  EditText titleText,contentText;
    private CharSequence t1,t2;//监听前的文本
    private CharSequence temp1,temp2;    // 监听中的文本
    private int n1=0,n2=0,num1=0,num2=0;//记录内容edittext字数
    private ImageButton return_ib,save_ib,suo_ib,kaisuo_ib,tag_ib;
    AlertDialog.Builder builder,builder2;
    // GreenDAO使用的变量
    private SQLiteDatabase db1,db2;
    private DaoMaster daoMaster1,daoMaster2;
    private DaoSession daoSession1,daoSession2;
    private diaryListDao dld;
    private diaryList dl;
    private diaryTagDao dtd;
    private diaryTag dt;
    private String str;
    private int id;
    private String update="0";

    private String t_date,t_title="",t_content,t_tag="全部",t_lock="true";//要写进表中的值
    private PopupWindow popupWindow;
    private TextView get_tag;
    private RecyclerView recyclerView;
    private writeDialogAdapter wAdapter;

    private diaryListDaoHelper dldh;
    private List<diaryList> dl_ById;
    private String g_date,g_title,g_content,g_tag,g_lock,pre_date,pre_sencond;//由主页传过来的position取出相对应的表数据
    private Intent intent1,intent2;
    private int desc,d_private;
    private String compare_title,compare_content,compare_lock;
    private TextView addTag,checkTag,default_tv;
    private EditText tag_et;
    private String get_editview_tag;
    private diaryTagDaoHelper dtdh;
    private List<diaryTag> diaryTag;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.colorPrimary_two);//通知栏所需颜色
        }
        setContentView(R.layout.pink_write);
        InitDAO_tag();
        InitDAO_list();
        initView();
        actionbarInit();
        intent1 = getIntent();// 获取意图对象
        if(intent1.getExtras()!=null){
            String date = intent1.getStringExtra("data1");//获取传递的值
            update = intent1.getStringExtra("data2");
            desc = Integer.parseInt(intent1.getStringExtra("data3"));
            d_private = Integer.parseInt(intent1.getStringExtra("data4"));
            compare_title=intent1.getStringExtra("data5");
            compare_content=intent1.getStringExtra("data6");
            compare_lock=intent1.getStringExtra("data7");
            InitUpdate(date);
        }
        suoListener();
        kaisuoListener();
        returnIbListener();
        saveIbListener();
        titleTextListener();
        contentTextListener();
        setTextView();
        dateListener();
        timeListener();
        tagListener();
        initDialog();
//        deleteDialog();
    }
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
    public void InitUpdate(String date){
      //  LinearLayout ll=(LinearLayout) findViewById(R.id.write_main);
        dl_ById=dldh.selectByDate(date);
        g_date=dl_ById.get(0).getDate();
        String s[]=g_date.split("\\:");
        pre_sencond=s[2];
        pre_date=dl_ById.get(0).getDate();
        g_title=dl_ById.get(0).getTitle();
        g_content=dl_ById.get(0).getContent();
        g_tag=dl_ById.get(0).getTag();
        g_lock=dl_ById.get(0).getLock();
        titleText.setText(g_title);
        contentText.setText(g_content);
        if(g_lock.equals("true")){
            suo_ib.setVisibility(View.GONE);
            kaisuo_ib.setVisibility(View.VISIBLE);
        }
        else{
            suo_ib.setVisibility(View.VISIBLE);
            kaisuo_ib.setVisibility(View.GONE);
        }
    }
    private void InitDAO_tag() {
        DaoMaster.DevOpenHelper helper1 = new DaoMaster.DevOpenHelper(this, "diary_Tag.db", null);
        db1 = helper1.getWritableDatabase();
        daoMaster1 = new DaoMaster(db1);//代表着一个数据库的连接
        daoSession1 = daoMaster1.newSession();//可以让我们使用一些Entity的基本操作和获取Dao操作类
        dtd = daoSession1.getDiaryTagDao();
        dtdh=new diaryTagDaoHelper(dtd);
    }
    private void InitDAO_list(){
        DaoMaster.DevOpenHelper helper2 = new DaoMaster.DevOpenHelper(this, "diary_List.db", null);
        db2 = helper2.getWritableDatabase();
        daoMaster2 = new DaoMaster(db2);//代表着一个数据库的连接
        daoSession2 = daoMaster2.newSession();//可以让我们使用一些Entity的基本操作和获取Dao操作类
        dld = daoSession2.getDiaryListDao();
    }
    public void initView(){
        actionBar = getSupportActionBar();
        contentText=(EditText) findViewById(R.id.et_content);
        titleText=(EditText) findViewById(R.id.et_title);
    }
    public void actionbarInit(){
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
        if (actionBar != null) {
            actionBar.setCustomView(R.layout.write_actionbar_custom);//设置自定义的布局
        }
        return_ib=(ImageButton) findViewById(R.id.return_button);
        save_ib=(ImageButton) findViewById(R.id.save_button);
        suo_ib=(ImageButton) findViewById(R.id.write_ab_suo);
        kaisuo_ib=(ImageButton) findViewById(R.id.write_ab_kaisuo);
        time1=(TextView) findViewById(R.id.write_ab_tv1);
        time2=(TextView) findViewById(R.id.write_ab_tv2);
    }
    public void suoListener(){//监听锁
        suo_ib.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(intent1.getExtras()!=null){
                    kaisuo_ib.setVisibility(View.VISIBLE);
                    suo_ib.setVisibility(View.GONE);
                    Toast.makeText(PinkWrite.this, "取消私密日记", Toast.LENGTH_SHORT).show();
                    t_lock="true";
                    g_lock=t_lock;
                    return_ib.setVisibility(View.GONE);
                    save_ib.setVisibility(View.VISIBLE);
                }
                else{
                    kaisuo_ib.setVisibility(View.VISIBLE);
                    suo_ib.setVisibility(View.GONE);
                    Toast.makeText(PinkWrite.this, "取消私密日记", Toast.LENGTH_SHORT).show();
                    t_lock="true";
                }


            }
        });
    }
    public void kaisuoListener(){//监听开锁
        kaisuo_ib.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(intent1.getExtras()!=null){
                    suo_ib.setVisibility(View.VISIBLE);
                    kaisuo_ib.setVisibility(View.GONE);
                    t_lock="false";
                    Toast.makeText(PinkWrite.this, "已设为私密日记", Toast.LENGTH_SHORT).show();
                    g_lock=t_lock;
                    return_ib.setVisibility(View.GONE);
                    save_ib.setVisibility(View.VISIBLE);
                }
                else{
                    suo_ib.setVisibility(View.VISIBLE);
                    kaisuo_ib.setVisibility(View.GONE);
                    t_lock="false";
                    Toast.makeText(PinkWrite.this, "已设为私密日记", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
    public void returnIbListener(){//监听返回按钮
        return_ib.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(intent1.getExtras()==null) finish();
                else{
                    intent2 =new Intent(PinkWrite.this,PinkMain.class);// 添加点击响应事件
                    intent2.putExtra("data1",desc+""); //设置传递键值对
                    intent2.putExtra("data2",d_private+""); //设置传递键值对
                    startActivity(intent2);//启动
                    finish();
                }
            }
        });
    }
    public void saveIbListener(){//监听保存按钮
        save_ib.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(intent1.getExtras()==null)insertDiary();
                else updateDiary();
                finish();

            }
        });
    }
    public void titleTextListener(){//监听标题EditText
        titleText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp1=s;
                num2=temp1.length();
            }
            @Override
            public void afterTextChanged(Editable s) {
                if(intent1.getExtras()!=null){
                    if(compare_title.equals(temp1)){
                        t_title=titleText.getText().toString();
                        g_title=t_title;
                    }
                    else{
                        return_ib.setVisibility(View.GONE);
                        save_ib.setVisibility(View.VISIBLE);
                        t_title=titleText.getText().toString();
                        g_title=t_title;
                    }
                }
                else{
                    t_title=titleText.getText().toString();
                    g_title=t_title;
                }
            }
        });
    }
    public void contentTextListener(){//监听内容EditText
        contentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {temp2=s;}
            @Override
            public void afterTextChanged(Editable s) {
                num1=temp2.length();
                t_content=contentText.getText().toString();
                g_content=t_content;
                if(num1!=0){
                    return_ib.setVisibility(View.GONE);
                    save_ib.setVisibility(View.VISIBLE);
                }
                else{
                    return_ib.setVisibility(View.VISIBLE);
                    save_ib.setVisibility(View.GONE);
                }
            }
        });
    }
    public void setTextView(){//给textview写东西

        nowTime();
        if(update.equals("0")){
            if(hour<10||minute<10){
                if(hour<10){
                    n_hour="0"+hour;
                    if(minute<10){
                        n_minute="0"+minute;
                        time2.setText("/"+n_hour+":"+n_minute);
                    }
                    else time2.setText("/"+n_hour+":"+minute);
                }
                else{
                    if(minute<10){
                        n_minute="0"+minute;
                        time2.setText("/"+hour+":"+n_minute);
                    }
                }
            }
            else{
                time2.setText("/"+hour+":"+minute);
            }
            time1.setText(month+"月"+day+"日");
        }
        else{
            String s1[]=g_date.split("\\/");
            String s2=s1[1];
            String s3[]=s1[2].split("\\:");
            String s4=s3[0];
            String s5=s3[1];
            g_date=s1[0]+"/"+s2+"/"+s4+":"+s5;
            time1.setText(s2);time2.setText("/"+s4+":"+s5);
        }
    }
    public void nowTime(){//获取当前时间
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH)+1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
        hour = calendar.get(Calendar.HOUR_OF_DAY);
        minute = calendar.get(Calendar.MINUTE);
        second = calendar.get(Calendar.SECOND);
    }
    public void dateListener(){//监听日期按钮的点击
        if(intent1.getExtras()==null){
            time1.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    datePicker();
                }
            });
        }

    }
    public void datePicker(){//日期选择器
        final DatePickerDialog datePickerDialog = new DatePickerDialog(this, null,year, month-1, day);
        datePickerDialog.setCancelable(true);
        datePickerDialog.setCanceledOnTouchOutside(true);
        datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "完成",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker picker = datePickerDialog.getDatePicker();
                        picker.setMaxDate(new Date().getTime());
                        get_year = picker.getYear();
                        get_month = picker.getMonth();
                        get_day = picker.getDayOfMonth();
                        time1.setText((++get_month)+"月"+get_day+"日");
                    }
                });
        datePickerDialog.show();

    }
    public void timeListener(){//监听时间按钮的点击
        if(intent1.getExtras()==null){
            time2.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    timePicker();
                }
            });
        }

    }
    private void timePicker() {//时间选择器
        final TimeDialog timeDialog = new TimeDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                get_hour=""+hourOfDay;
                get_minute=""+minute;
                if(hourOfDay<10){
                    get_hour="0"+hourOfDay;
                }
                if(minute<10){
                    get_minute="0"+minute;
                }
                time2.setText("/"+get_hour+":"+get_minute);
            }
        }, hour, minute, true);
        timeDialog.setCancelable(true);
        timeDialog.setCanceledOnTouchOutside(true);
        timeDialog.show();
    }
    private void initDialog() {//退出时弹出对话框确认是否退出
        builder = new AlertDialog.Builder(this).setIcon(R.drawable.heart)
                .setTitle("确定放弃此次编辑？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        dialog.dismiss();
                    }
                })
                .setNeutralButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if(intent1.getExtras()==null)insertDiary();
                        else updateDiary();
                        finish();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
    }
    @Override
    public void onBackPressed() {//按下底部返回键时
        if(intent1.getExtras()!=null){
            if(!g_title.equals(compare_title) || !g_lock.equals(compare_lock)){
                builder.show();
            }
            else{
                intent2 =new Intent(PinkWrite.this,PinkMain.class);// 添加点击响应事件
                intent2.putExtra("data1",desc+""); //设置传递键值对
                intent2.putExtra("data2",d_private+""); //设置传递键值对
                startActivity(intent2);//启动
                this.finish();
            }
        }
        else{
            if(num1!=0) builder.show();
            else this.finish();
        }

    }
    public void tagListener(){//监听tag按钮
        tag_ib=(ImageButton) findViewById(R.id.write_ab_bj);
        tag_ib.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                showPopupWindow();

            }
        });
    }
    private void showPopupWindow() {//设置底部弹出框
        t_tag="全部";
        List<diaryTag> tagList = dtd.loadAll();
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View parent_view=LayoutInflater.from(PinkWrite.this).inflate(R.layout.pink_write,null);
        View view = layoutInflater.inflate(R.layout.write_dialog, null);
        default_tv=(TextView) view.findViewById(R.id.default_tv);
        addTag=(TextView) view.findViewById(R.id.write_dialog_tv);
        defaultListener();
        addTagListener();
        recyclerView = (RecyclerView) view.findViewById(R.id.select);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));//设置线性管理器
        wAdapter = new writeDialogAdapter(tagList);
        recyclerView.setAdapter(wAdapter);
        popupWindow = new PopupWindow(view, 1000, 500);
        popupWindow.setContentView(view);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setAnimationStyle(R.style.BottomDialogAnimation);
        popupWindow.showAtLocation(findViewById(R.id.write_main),Gravity.BOTTOM,0,0);
        wAdapter.setOnItemClickListener(new writeDialogAdapter.ItemClickListener(){
            @Override
            public void onItemClick(View view,int position){
                get_tag=(TextView) view.findViewById(R.id.item_tv);
                t_tag=get_tag.getText().toString();
                popupWindow.dismiss();
            }
            @Override
            public boolean onItemLongClick(View view,int position){
                checkTag=(TextView)recyclerView.getChildAt(position).findViewById(R.id.item_tv);
                deleteDialog();
                builder2.show();
                return true;
            }
        });
    }
    public void defaultListener() {//监听全部标签按钮
        default_tv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            t_tag=default_tv.getText().toString();
                popupWindow.dismiss();
            }
        });
    }
    private void deleteDialog() {//退出时弹出对话框确认是否退出
        builder2 = new AlertDialog.Builder(this).setIcon(R.drawable.heart)
                .setTitle("确定删除标签？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteTag(checkTag);
                        popupWindow.dismiss();
                        showPopupWindow();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
    }
    public void addTagListener(){//监听弹出框中编辑标签按钮
        addTag.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                textAlertDialog();
            }
        });
    }
    public void textAlertDialog(){//弹出框填写需要添加的Tag
        LayoutInflater factory = LayoutInflater.from(PinkWrite.this);//提示框
        final View view = factory.inflate(R.layout.add_tag, null);

        new AlertDialog.Builder(PinkWrite.this).setIcon(R.drawable.heart)
                .setTitle("添加你喜欢的标签吧")//提示框标题
                .setView(view)
                .setPositiveButton("确定",//提示框的两个按钮
                        new android.content.DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                tag_et=(EditText)view.findViewById(R.id.tag_et);
                                get_editview_tag=tag_et.getText().toString();
                                insertTag();
                                dialog.dismiss();
                                popupWindow.dismiss();
                                showPopupWindow();
                            }
                        }).setNegativeButton("取消", null).create().show();
    }
    public void insertDiary(){//保存日记
        if(get_year!=year && get_year!=0){
            t_date=get_year+"/"+time1.getText().toString()+time2.getText().toString();
        }
        else t_date=year+"/"+time1.getText().toString()+time2.getText().toString();
        diaryList saveList=new diaryList();
        saveList.setTitle(t_title);
        saveList.setContent(t_content);
        saveList.setTag(t_tag);
        if(second<10){
            saveList.setDate(t_date+":0"+second);
        }
        else saveList.setDate(t_date+":"+second);
        saveList.setLock(t_lock);
        dld.insert(saveList);
    }
    public void updateDiary(){//更新日记
        diaryList updateList = dld.queryBuilder().where(diaryListDao.Properties.Date.eq(pre_date)).build().unique();
        if(updateList != null) {
            updateList.setDate(g_date+":"+pre_sencond);
            updateList.setTitle(g_title);
            updateList.setContent(g_content);
            updateList.setTag(g_tag);
            updateList.setLock(g_lock);
            dld.update(updateList);
            intent2 =new Intent(PinkWrite.this,PinkMain.class);// 添加点击响应事件
            intent2.putExtra("data1",desc+""); //设置传递键值对
            intent2.putExtra("data2",d_private+""); //设置传递键值对
            startActivity(intent2);//启动
            finish();
        } else {

        }
    }
    public void insertTag(){//判断添加的tag是否已经存在
        int num=dtdh.judgeByTag(get_editview_tag);
        if(num==0){
            diaryTag saveTag=new diaryTag();
            saveTag.setTag(get_editview_tag);
            dtd.insert(saveTag);
        }
        else{
            Toast.makeText(PinkWrite.this, "添加的标签已存在", Toast.LENGTH_SHORT).show();
        }
    }
    public void deleteTag(TextView checkTag){

        String tag=checkTag.getText().toString();
        dtdh.deleteByTag(tag);
    }
}
